import { Controller } from "egg";
import config from "../config";
import axios from "axios";
import * as fs from "fs";
import * as path from "path";

function success(data: any) {
  return {
    success: true,
    message: null,
    data,
    code: 1,
    timestamp: Date.now()
  };
}

function fail(message: string) {
  return {
    success: false,
    message,
    data: null,
    code: -1,
    timestamp: Date.now()
  };
}

console.log(fail);

/**
 * @Controller 萤石云Api接入 YsyController
 */
export default class YsyController extends Controller {
  /**
   * @summary 获取萤石云AccessToken
   * @description 获取萤石云AccessToken
   * @router GET /api/ysy/access-token
   * @response 200
   */
  async accessToken() {
    const cachePath = path.resolve(
      process.cwd(),
      "app",
      "controller",
      "temp.json"
    );

    const cacheStr = fs.readFileSync(cachePath).toString("utf-8");
    const cache = JSON.parse(cacheStr) as {
      accessToken: string;
      expireTime: number;
    };

    if (cache.expireTime === 0 || Date.now() >= cache.expireTime) {
      const url = new URL("https://open.ys7.com/api/lapp/token/get");
      url.searchParams.append("appKey", config.YSY_APP_KEY);
      url.searchParams.append("appSecret", config.YSY_APP_SECRET);
      const { data } = await axios.post(url.toString());
      if (data.code === "200") {
        fs.writeFileSync(cachePath, JSON.stringify(data.data, null, 2));
        this.ctx.body = success(data.data);
        this.ctx.status = 200;
      } else {
        this.ctx.body = fail(data.msg);
        this.ctx.status = 500;
      }
    } else {
      this.ctx.body = success(cache);
      this.ctx.status = 200;
    }
  }

  /**
   * @summary 获取萤石云设备列表
   * @description 获取萤石云设备列表
   * @router GET /api/ysy/device-list
   * @request query string *accessToken accessToken
   * @response 200
   */
  async deviceList() {
    const accessToken = this.ctx.request.query.accessToken;
    if (!accessToken) {
      this.ctx.body = fail("accessToken不能为空");
      this.ctx.status = 500;
    } else {
      const url = new URL("https://open.ys7.com/api/lapp/device/list");
      url.searchParams.append("accessToken", accessToken);
      const { data } = await axios.post(url.toString());
      if (data.code === "200") {
        this.ctx.body = success(data.data);
        this.ctx.status = 200;
      } else {
        this.ctx.body = fail(data.msg);
        this.ctx.status = 500;
      }
    }
  }

  /**
   * @summary 获取萤石云监控列表
   * @description 获取萤石云监控列表
   * @router GET /api/ysy/camera-list
   * @request query string *accessToken accessToken
   * @response 200
   */
  async cameraList() {
    const accessToken = this.ctx.request.query.accessToken;
    if (!accessToken) {
      this.ctx.body = fail("accessToken不能为空");
      this.ctx.status = 500;
    } else {
      const url = new URL("https://open.ys7.com/api/lapp/camera/list");
      url.searchParams.append("accessToken", accessToken);
      const { data } = await axios.post(url.toString());
      if (data.code === "200") {
        this.ctx.body = success(data.data);
        this.ctx.status = 200;
      } else {
        this.ctx.body = fail(data.msg);
        this.ctx.status = 500;
      }
    }
  }

  /**
   * @summary 开始云台控制
   * @description 开始云台控制
   * @router GET /api/ysy/constrol-start
   * @request query string *accessToken accessToken
   * @request query string *deviceSerial 设备序列号
   * @request query integer *channelNo 通道号
   * @request query integer *direction 操作命令：0-上，1-下，2-左，3-右，4-左上，5-左下，6-右上，7-右下，8-放大，9-缩小，10-近焦距，11-远焦距
   * @request query integer speed 云台速度：0-慢，1-适中，2-快，海康设备参数不可为0(不传，默认为1)
   * @response 200
   */
  async startCameraControl() {
    const accessToken = this.ctx.request.query.accessToken;
    const deviceSerial = this.ctx.request.query.deviceSerial;
    const channelNo = this.ctx.request.query.channelNo;
    const direction = this.ctx.request.query.direction;
    const speed = this.ctx.request.query.speed || "1";
    if (!accessToken || !deviceSerial || !channelNo || !direction) {
      this.ctx.body = fail(
        "accessToken、deviceSerial、channelNo、direction为必需参数"
      );
      this.ctx.status = 500;
    } else {
      const url = new URL("https://open.ys7.com/api/lapp/device/ptz/start");
      url.searchParams.append("accessToken", accessToken);
      url.searchParams.append("deviceSerial", deviceSerial);
      url.searchParams.append("channelNo", channelNo);
      url.searchParams.append("direction", direction);
      url.searchParams.append("speed", speed);
      const { data } = await axios.post(url.toString());
      if (data.code === "200") {
        this.ctx.body = success(data.data);
        this.ctx.status = 200;
      } else {
        this.ctx.body = fail(data.msg);
        this.ctx.status = 500;
      }
    }
  }

  /**
   * @summary 停止云台控制
   * @description 停止云台控制
   * @router GET /api/ysy/constrol-stop
   * @request query string *accessToken accessToken
   * @request query string *deviceSerial 设备序列号
   * @request query integer *channelNo 通道号
   * @request query integer direction 操作命令(可不传)：0-上，1-下，2-左，3-右，4-左上，5-左下，6-右上，7-右下，8-放大，9-缩小，10-近焦距，11-远焦距
   * @response 200
   */
  async stopCameraControl() {
    const accessToken = this.ctx.request.query.accessToken;
    const deviceSerial = this.ctx.request.query.deviceSerial;
    const channelNo = this.ctx.request.query.channelNo;
    const direction = this.ctx.request.query.direction;
    if (!accessToken || !deviceSerial || !channelNo) {
      this.ctx.body = fail("accessToken、deviceSerial、channelNo为必需参数");
      this.ctx.status = 500;
    } else {
      const url = new URL("https://open.ys7.com/api/lapp/device/ptz/stop");
      url.searchParams.append("accessToken", accessToken);
      url.searchParams.append("deviceSerial", deviceSerial);
      url.searchParams.append("channelNo", channelNo);
      if (direction) {
        url.searchParams.append("direction", direction);
      }
      const { data } = await axios.post(url.toString());
      console.log(data);
      if (data.code === "200") {
        this.ctx.body = success(data.data);
        this.ctx.status = 200;
      } else {
        this.ctx.body = fail(data.msg);
        this.ctx.status = 500;
      }
    }
  }
}
